/**
* Description: 胸牌管理
*
* Created by hrx on 2023/10/16
*/
<template>
  <div class="region">
    <!-- 头部搜索栏 -->
    <div class="top-title">区域管理</div>
    <!--      内容块-->
    <div class="list">
      <div class="left">
        <div class="left-top">
          <el-button link :icon="CirclePlus" @click="addRegionInfo('层级')">创建层级</el-button>
        </div>
        <div class="left-tree">
          <el-tree
            style="padding-left: 15px;margin-bottom: 70px"
            ref="treeRef"
            :default-expanded-keys="[0]"
            node-key="id"
            :data="regionLevelTreeList"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :expand-on-click-node="false"
            :check-on-click-node="true"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <div style="flex:1;" class="textW">
                  <tool-tip :text="node.label" :max-length="11" :show-line-num="1"/>
                </div>
                <span class="el-dropdown-link" @click.stop>
                <el-dropdown
                  v-if="data.id != 0"
                  trigger="click"
                  @command="command => treeBtnMore(command, data)"
                >
                  <span class="el-dropdown-link">
                   <el-icon style="margin-right: 10px"><More/></el-icon>
                  </span>
                  <template #dropdown>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="delete">删除</el-dropdown-item>
                  </el-dropdown-menu>
                  </template>
                </el-dropdown>
                  </span>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
      <div class="right">
        <div class="right-top">
          <div class="add-btn">
            <el-button type="primary" :icon="Plus" @click="addRegionInfo('区域')">创建区域</el-button>
          </div>
          <div class="search">
            <el-form
              :model="form"
              ref="formRef"
              inline
              class="searchForm"
            >
              <el-form-item>
                <el-input
                  style="width: 160px; height: 36px"
                  placeholder="请输入区域名称"
                  v-model="form.regionName"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getRegionListData">搜索</el-button>
                <el-button @click="reset('form')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="region-list" v-if="checkRegion">
          <template v-for="item in regionList" :key="item.id">
            <region-item
              v-if="item.regionInfoVOList && item.regionInfoVOList.length > 0"
              :region="item"
              @edit-region="editRegionInfo"
              @after-submit="afterSubmit"
              @point-view="pointViewInfo"/>
          </template>
        </div>
        <div class="not-data-img" v-else>
          <img :src="$CONSTANTS.NOT_DATA_IMG" style="width: 200px; height: 250px">
        </div>
      </div>
    </div>
    <editRegion
      ref="editRegionRef"
      :mode="editRegionMode"
      :options-region="regionLevelTreeList[0].children"
      :regionClassify="regionClassify"
      @after-submit="afterSubmit"
    />
    <point-view ref="pointViewRef" :region-info="pointViewRegion"></point-view>
  </div>
</template>

<script setup lang="ts">
import {CirclePlus, Plus} from '@element-plus/icons-vue'
import $CONSTANTS from "@/constants/globalConstants"
import {REGION_CLASSIFY} from '@/constants/mapConstants'
import {
  delRegionApi,
  getRegionLevelTreeApi,
  getRegionListDataApi,
  type queryRegionListParam,
  type regionDetailDTO,
  type regionInfoDTO
} from "@/api/region";
import RegionItem from "@/components/systemConfig/region/regionItem.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import PointView from "@/components/systemConfig/region/pointView.vue";
import {reactive} from "vue";

const treeRef = ref();
const editRegionRef = ref();
const pointViewRef = ref();

const regionLevelTreeList = ref<Array<regionInfoDTO>>([
  {
    children: []
  }
])
const regionList = ref<Array<regionDetailDTO>>([]);
const defaultProps = {
  children: 'children',
  label: 'regionName',
}
const form = reactive<queryRegionListParam>({
  id: undefined,
  regionName: undefined,
  merchantCode: '1'
})

const regionClassify = ref<number | undefined>(1)
const editRegionMode = ref<string | undefined>('add')
const pointViewRegion = reactive<regionInfoDTO>({})

const checkRegion = computed(() => {
  let flag = false;
  for (let i = 0; i < regionList.value.length; i++) {
    let item = regionList.value[i];
    if (item.regionInfoVOList && item.regionInfoVOList.length > 0) {
      flag = true
      return flag;
    }
  }
  return flag;
})

const init = () => {
  getRegionLevelTree()
  getRegionListData();
}

const getRegionLevelTree = async () => {
  let res = await getRegionLevelTreeApi();
  regionLevelTreeList.value =
    [{
      children: res.data.data,
      regionName: '全部区域',
      id: 0
    }]
  await nextTick(() => {
    treeRef.value.setCurrentKey(0);
  })
}

const getRegionListData = async () => {
  let res = await getRegionListDataApi(form)
  regionList.value = res.data.data;
}


const handleNodeClick = (val: regionInfoDTO) => {
  form.id = val.id == 0 ? undefined : val.id;
  getRegionListData();
}

const treeBtnMore = (command: string, data: regionInfoDTO) => {
  if (command == 'edit') {
    editRegionInfo(data, '层级');
  } else if (command == 'delete') {
    delLevel(data);
  }
}

const pointViewInfo = (data: regionInfoDTO) => {
  pointViewRef.value.drawer = true;
  Object.assign(pointViewRegion, data)
}

const delLevel = (data: regionInfoDTO) => {
  ElMessageBox.confirm('确认要删除所选层级吗?', '提示', {type: 'warning',})
    .then(async () => {
      let res = await delRegionApi({
        id: data.id,
        regionClassify: REGION_CLASSIFY['层级'].VALUE
      })
      if (res.data.code == 0) {
        form.id = undefined;
        ElMessage.success('删除成功')
        init();
      }
    })
}

const addRegionInfo = (key: string) => {
  regionClassify.value = REGION_CLASSIFY[key].VALUE;
  editRegionMode.value = 'add';
  editRegionRef.value.dialogFormVisible = true;
}

const editRegionInfo = (data: regionInfoDTO, type: string) => {
  regionClassify.value = REGION_CLASSIFY[type].VALUE;
  editRegionMode.value = 'edit';
  editRegionRef.value.dialogFormVisible = true;
  data.subId = diGuiHx(data.parentId, regionLevelTreeList)
  if (type == '区域') data.id = data.regionId;
  Object.assign(editRegionRef.value.form, data);
}

const afterSubmit = () => {
  form.id = undefined;
  init();
}

const reset = (type: string) => {
  form.regionName = '';
  getRegionListData();
}

const diGuiHx = (key: any, treeData: any) => {    // 递归回显
  let arr: Array<number> = []; // 在递归时操作的数组
  let returnArr: Array<number> = []; // 存放结果的数组
  let num = 0; // 定义全局层级
  // 定义递归函数
  function childrenEach(childrenData: any, nums: number) {
    for (let j = 0; j < childrenData.length; j++) {
      num = nums; // 将执行的层级赋值 到 全局层级
      arr[nums] = childrenData[j].id;
      if (childrenData[j].id === key) {
        returnArr = arr.slice(0, nums + 1); // 将目前匹配的数组，截断并保存到结果数组，
        if (returnArr.length > 1) returnArr.shift();
        break;
      } else {
        if (childrenData[j].children) {
          num++;
          childrenEach(childrenData[j].children, num);
        }
      }
    }
    return returnArr;
  }

  return childrenEach(treeData.value, num);
}

onMounted(() => {
  init();
})

</script>

<style lang="scss" scoped>
.region {
  width: 100%;
  height: 100%;
  overflow: hidden;
  .top-title {
    background-color: #FFF;
    padding: 20px;
    font-weight: 700;
    color: $text-theme-color;
    font-size: 18px;
    border-bottom: 3px $background-color solid;

  }
  .list {
    display: flex;
    height: 100vh;
    .left {
      width: 240px;
      border-right: 15px $background-color solid;
      background-color: #FFF;
      .left-top {
        text-align: center;
        height: 80px;
        line-height: 80px;
        border-bottom: 3px solid $background-color;
        :deep(.is-link) {
          color: $theme-color;
        }
      }
      .left-tree {
        //flex: 1;
        min-width: 17%;
        background-color: #ffffff;
        overflow: auto;
        height: 80vh;
        :deep(.el-tree) {
          padding-left: 0 !important;
        }
        :deep(.el-tree-node__content) {
          height: 40px;
          &:hover {
            background-color: #F5F7FA;
            color: #606266;
          }
        }
        :deep(.el-tree-node.is-current > .el-tree-node__content) {
          background-color: $theme-color !important;
          color: #FFFFFF;
        }
        :deep(.el-button) {
          height: 40px !important;
        }
        :deep(.el-dropdown) {
          color: inherit;
        }
        .alltrees {
          width: 100%;

          p {
            width: 100%;
            height: 40px;
            line-height: 36px;
            background: #f5f7fd;
            color: #778ca2;
            text-align: left;
            margin-left: -10px;
          }
        }
        .btn {
          border: none;
          background: #FFFFFF;
          width: 100%;
          text-align: left;
          color: #606266;
        }
        .btn:focus {
          background-color: $theme-color;
          color: #FFFFFF;
        }
        .btn:hover {
          background-color: #F5F7FA;
          color: #606266;
        }

        .custom-tree-node {
          display: flex;
          align-items: center;
          font-size: 14px;
          width: 100%;
          .textW {
            width: 115px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
    .right {
      flex: 1;
      .right-top {
        height: 56px;
        margin-top: 10px;
        margin-bottom: 20px;
        background-color: #FFF;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .add-btn {
          margin-left: 20px;
        }
        .search {
          .searchForm {
            height: 36px;
            margin: auto 0;
            padding-right: 20px;
          }
        }
      }
      .region-list {
        height: 75vh;
        overflow-x: scroll;
      }
      .not-data-img {
        margin: 180px auto;
        width: 200px;
      }
    }
  }
}
</style>